#!/bin/bash
# 定义需要打包的程序目录
program_dir="output"
app_name="tss"

#获取脚本运行时传入的参数，表示要打包的分支。若有，则当做版本号；否则提取文件VERSION中的内容
GIT_BRANCH=$1
if [ -n $GIT_BRANCH ]; then
  #截取/末尾的字符串
  VERSION=${GIT_BRANCH##*/}
fi

if [ -z ${VERSION} ]; then
  VERSION="0.0.0"
fi
echo "编译版本号: ${VERSION}"

# 执行交叉编译
rm -rf ${program_dir}
export GOPROXY=https://mirrors.aliyun.com/goproxy/,direct
go mod tidy
go mod vendor


build(){
    GOOS=$1
    GOARCH=$2
    output_flag="${program_dir}/${app_name}-${GOOS}-${GOARCH}"
    if [ "$GOOS" = "windows" ]; then
      output_flag="${program_dir}/${app_name}-${GOOS}-${GOARCH}.exe"
    fi

    GOOS=$GOOS GOARCH=${GOARCH} go build -o ${output_flag} main.go

    # 添加错误处理，确保在构建失败时脚本能够退出
    if [ $? -ne 0 ]; then
      echo "构建失败: ${output_flag}"
      exit 1
    fi

    echo "成功构建: ${output_flag}"
}
build linux amd64
#build linux amd64
#build linux arm

#build windows amd64
#build windows arm64
#build darwin amd64
build darwin arm64


# 遍历程序目录下的所有文件和文件夹
for file in $(ls $program_dir)
do
    deploy_file=''
    rm -rf tss
    mkdir tss
    cp -R ui tss
    if [ "$(echo ${file} | grep "windows")" != "" ]; then
      mv "${program_dir}/$file" tss/tss.exe
      cp start.bat tss/
      # 如果是文件，则直接打包成tar包
      deploy_file="${file%.*}-${VERSION}.zip"
      zip -r ${deploy_file} tss
    else
      if [ "$(echo ${file} | grep "linux")" != "" ]; then
        cp start.sh tss/
        cp stop.sh tss/
      else
        cp start_mac.sh tss/start.sh
      fi
      mv "${program_dir}/$file" tss/tss
      # 如果是文件，则直接打包成tar包
      deploy_file="${file}-${VERSION}.tar.gz"
      tar -czf ${deploy_file} tss
    fi
    mv ${deploy_file} ${program_dir}/
done
rm -rf tss

